package com.ccp.dev.workflow.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.core.util.log.SysAuditThreadLocalHolder;
import com.ccp.dev.form.model.FormField;
import com.ccp.dev.form.service.FormFieldService;
import com.ccp.dev.workflow.model.ActDefModel;
import com.ccp.dev.workflow.model.BpmDefVar;
import com.ccp.dev.workflow.service.ActDefModelService;
import com.ccp.dev.workflow.service.BpmDefVarService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ClassDescribe:流程变量控制器类
 * @author :jiayueqiao
 * Date: 2019-05-24
 * Since:1
 */
@Controller
@RequestMapping(UrlConstants.PROJECT_ROOT +UrlConstants.PROJECT_MODULE_WORKFLOW+"/bpmDefVar")
@Action(ownermodel=SysAuditModelType.PROCESS_MANAGEMENT)
public class BpmDefVarController extends SysBaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(BpmDefVarController.class);
    @Resource
    private BpmDefVarService bpmDefVarService;
    @Resource
    private FormFieldService formFieldService;
    @Resource
    private ActDefModelService actDefModelService;


    /**
     * 流程变量管理页面
     * @return String
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description = "查看流程定义管理-设置-变量管理页面",detail="查看流程定义管理-设置-变量管理页面")
    public String viewList(HttpServletRequest request,Model model) {
        String modelId = RequestUtil.getString(request,"modelId");
        model.addAttribute("modelId",modelId);
        return getAutoView();
    }

    /**
     * 流程变量管理添加或修改页面
     * @return String
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + UrlConstants.MODULE_FUNCTION_ADD_UPDATE)
    @Action(description = "操作添加或修改流程变量页面",detail="操作添加或修改流程变量页面")
    public String viewAdd(HttpServletRequest request,Model model) {
        String modelId = RequestUtil.getString(request,"modelId");
        model.addAttribute("modelId",modelId);
        String varId = RequestUtil.getString(request,"varId");
        model.addAttribute("varId",varId);
        return getAutoView();
    }


    /**
     * 根据流程模型id获取变量列表
     * @param modelId 流程模型定义id
     * @return 模型列表
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_LIST)
    @Action(description = "查询流程变量列表数据",detail = "查询流程变量列表数据<#if fl>成功<#else>失败</#if>")
    @ResponseBody
    public ResultData list(@RequestParam String modelId) {
        try{
            List<BpmDefVar> list = bpmDefVarService.queryByModelId(modelId);
            SysAuditThreadLocalHolder.putParamerter("fl", true);
            return getResultDataSuccess("operation.success", list);
        }catch(Exception e){
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 删除流程变量
     * @param request request
     * @return ResultData
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_DELETE)
    @ResponseBody
    @Action(description = "删除流程变量定义",
            detail="<#if varIds!=\"\">删除流程${actDefModel.description}-${actDefModel.modelKey}的流程变量，流程变量id包括${varIds},操作<#if fl>成功<#else>失败</#if></#if>"
    )
    public ResultData del(HttpServletRequest request){
        String[] lAryId = RequestUtil.getStringAryByStr(request, "varIds");
        if(null==lAryId){
            return getResultDataError("flow.variable.not.select");
        }
        //2019-11-13 jyq修改，记录详细日志
        String varIds = request.getParameter("varIds");
        SysAuditThreadLocalHolder.putParamerter("varIds", varIds);
        BpmDefVar bpmDefVar = bpmDefVarService.getOneById(lAryId[0]);
        String modelId = bpmDefVar.getModelId();
        ActDefModel actDefModel = actDefModelService.getOneById(modelId);
        SysAuditThreadLocalHolder.putParamerter("actDefModel", actDefModel);
        try {
            bpmDefVarService.delVarsByIdArray(lAryId);
            SysAuditThreadLocalHolder.putParamerter("fl", true);
            return getResultDataSuccess("delete.success");
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage());
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("delete.failure");
        }
    }

    /**
     * 根据变量id查询明细
     * @param varId 变量id
     * @return ResultData
     */
    @RequestMapping("/detail")
    @Action(description = "查询流程变量明细数据",detail="查询流程变量明细数据<#if fl>成功<#else>失败</#if>")
    @ResponseBody
    public ResultData detail(@RequestParam String varId){
        try{
            BpmDefVar bpmDefVar= bpmDefVarService.getOneById(varId);
            SysAuditThreadLocalHolder.putParamerter("fl", true);
            return getResultDataSuccess("operation.success", bpmDefVar);
        }catch (Exception ex){
            LOGGER.error(ex.getMessage());
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 新增或修改
     * @param bpmDefVar 流程变量对象
     * @return 保存结果
     */
    @RequestMapping(UrlConstants.MODULE_FUNCTION_SAVE)
    @Action(description = "编辑流程变量定义",detail="编辑流程变量定义<#if fl>成功<#else>失败</#if>")
    @ResponseBody
    public ResultData save(@RequestBody BpmDefVar bpmDefVar){
        try{
            String varId = bpmDefVar.getVarId();
            String varName = bpmDefVar.getVarName();
            String varKey = bpmDefVar.getVarKey();
            String modelId = bpmDefVar.getModelId();
            if(StringUtil.isEmpty(varId)){
                //新增流程变量
                //查询流程变量名称或key是否存在
                boolean isExist=bpmDefVarService.isVarNameOrVarKeyExist(varName,varKey,modelId);
                if(!isExist){
                    //新增操作
                    bpmDefVar.setVarId(UUIDUtils.getUUIDFor32());
                    int rs = bpmDefVarService.add(bpmDefVar);
                    if (rs > 0) {
                        return getResultDataSuccess("flow.variable.save.success");
                    } else {
                        return getResultDataError("flow.variable.save.failure");
                    }
                }else{
                    return getResultDataError("flow.variable.exist");
                }
            }else{
                //修改流程变量
                BpmDefVar oldVar=bpmDefVarService.getOneById(varId);
                if(!oldVar.getVarName().equals(varName)){
                    //修改变量名称
                    boolean isExist=bpmDefVarService.isVarNameOrVarKeyExist(varName,null,modelId);
                    if(isExist){
                        return getResultDataError("flow.variable.exist.name");
                    }
                }
                if(!oldVar.getVarKey().equals(varKey)){
                    //修改变量key
                    boolean isExist=bpmDefVarService.isVarNameOrVarKeyExist(null,varKey,modelId);
                    if(isExist){
                        return getResultDataError("flow.variable.exist.key");
                    }
                }
                //修改操作
                int rs = bpmDefVarService.update(bpmDefVar);
                if (rs > 0) {
                    SysAuditThreadLocalHolder.putParamerter("fl", true);
                    return getResultDataSuccess("update.success");
                } else {
                    SysAuditThreadLocalHolder.putParamerter("fl", false);
                    return getResultDataError("update.failure");
                }
            }
        }catch(Exception ex){
            LOGGER.error(ex.getMessage());
            SysAuditThreadLocalHolder.putParamerter("fl", false);
            return getResultDataError("operation.failure");
        }
    }

    /**
     * 查询流程变量
     * @param request 参数
     * @return ResultData
     */
    @RequestMapping("/getFlowVars")
    @Action(description = "查询流程变量")
    @ResponseBody
    public ResultData getFlowVars(HttpServletRequest request){
        String modelId = RequestUtil.getString(request,"modelId");
        ActDefModel actDefModel = actDefModelService.getOneById(modelId);
        String defId = actDefModel.getProcDefId();
        String parentProcDefId = RequestUtil.getString(request,"parentProcDefId");
        List<Map<String,String>> defVarList = new ArrayList<>();
        List<FormField> fieldList;
        fieldList= formFieldService.queryFlowVarByFlowProcDefIdOrParentProcDefId(defId,parentProcDefId);
        for(FormField field:fieldList){
            Map<String,String> fieldVarMap = new HashMap<>(2);
            fieldVarMap.put("varKey",field.getFieldName());
            fieldVarMap.put("varName",field.getFieldDesc());
            defVarList.add(fieldVarMap);
        }
        //流程变量定义中的流程变量
        List<BpmDefVar> bpmDefVars= bpmDefVarService.queryByModelId(modelId);
        for (BpmDefVar defVar:bpmDefVars) {
            if (defVar!=null) {
                Map<String,String> defVarMap = new HashMap<>(2);
                defVarMap.put("varKey",defVar.getVarKey());
                defVarMap.put("varName",defVar.getVarName());
                defVarList.add(defVarMap);
            }
        }
        return getResultDataSuccess("operation.success",defVarList);
    }
}
